﻿
CREATE PROCEDURE [dbo].[proc_ysh_Order]
	(
		@OId uniqueidentifier
		,@CusId	uniqueidentifier
		,@CusName	nvarchar(50)
		,@CusPerson	nvarchar(50)
		,@CusPersonTel	nvarchar(50)
		,@CusDescription	nvarchar(1000)
		,@CusEstimate	nvarchar(200)
		,@TypeId	int
		,@TypeName	nvarchar(50)
		,@WayId	int
		,@WayName	nvarchar(50)
		,@ProcessId	int
		,@ProcessName	nvarchar(50)
		,@Salesman	nvarchar(50)
		,@SalesmanAccount	nvarchar(50)
		,@TradeDate	datetime
		,@CreateDate	datetime
		,@YingShouPrice	decimal(18, 2)
		,@ShiShouPrice	decimal(18, 2)
		,@Discount	nvarchar(50)
		,@PaymentTypeId	int
		,@PaymentType	nvarchar(50)
		,@BankId	int
		,@Bank	nvarchar(50)
		,@PaymentDescription	nvarchar(200)
		,@OtherDescription	nvarchar(1000)
		,@DepId	int
		,@CompanyId	int
		,@StateId int
,@Creater varchar(30)
	)
AS
Begin Tran
		if @CompanyId=0 Or @DepId =0
			Select @Salesman=EName,@DepId=DepartmentId,@CompanyId=CompanyId From Employee Where UserName=@SalesmanAccount
		else
			Select @Salesman=EName From Employee Where UserName=@SalesmanAccount

		Insert Into [Order]
		(
			OId
			,CusId
			,CusName
			,CusPerson
			,CusPersonTel
			,CusDescription
			,CusEstimate
			,TypeId
			,TypeName
			,WayId
			,WayName
			,ProcessId
			,ProcessName
			,Salesman
			,SalesmanAccount
			,TradeDate
			,CreateDate
			,YingShouPrice
			,ShiShouPrice
			,Discount
			,PaymentTypeId
			,PaymentType
			,BankId
			,Bank
			,PaymentDescription
			,OtherDescription
			,DepId
			,CompanyId
			,StateId
			,IsGreen
,FinanceRenLingDate
,ExCompanyId,AuditDate
		)
		Values
		(
			@OId
			,@CusId
			,@CusName
			,@CusPerson
			,@CusPersonTel
			,@CusDescription
			,@CusEstimate
			,@TypeId
			,@TypeName
			,@WayId
			,@WayName
			,@ProcessId
			,@ProcessName
			,@Salesman
			,@SalesmanAccount
			,@TradeDate
			,@CreateDate
			,@YingShouPrice
			,@ShiShouPrice
			,@Discount
			,@PaymentTypeId
			,@PaymentType
			,@BankId
			,@Bank
			,@PaymentDescription
			,@OtherDescription
			,@DepId
			,@CompanyId
			,@StateId
			,0
			,@CreateDate
,@CompanyId,@CreateDate--审核日期与新增日期相同
		)
		Insert Into Order_PaymentRecord
		(
			OId
			,CusId
			,CusName
			,SalesmanAccount
			,Salesman
			,CreateDate
			,Prices
			,PaymentTypeId
			,PaymentType
			,BankId
			,Bank
			,SWId
			,SWName
,FinanceDate
			,FinanceFlag
			,CompanyId
,Description
		)
		Values
		(
			@OId
			,@CusId
			,@CusName
			,@SalesmanAccount
			,@Salesman
			,@CreateDate
			,@ShiShouPrice
			,@PaymentTypeId
			,@PaymentType
			,@BankId
			,@Bank
			,1
			,'首款'
			,@CreateDate
			,1
			,@CompanyId
,@OtherDescription
		)
		Update Order_Item Set OId=@OId,Occupancy=NULL,TradeDate=@TradeDate Where Occupancy=@Creater
		Update Customer Set StateId=2,ProtectId=3,ProtectName=NULL,ProtectDate=NULL Where CustomerId=@CusId

   If @@error <> 0  --发生错误
		Begin
			RollBack Tran
			Return
		End
    Else
		Begin
			Commit Tran
			Return    --执行成功
End
